package com.yesallchina.wxapp.officialaccount.api.beans;


import com.yesallchina.wxapp.officialaccount.api.enums.MessageEventTypeEnum;
import com.yesallchina.wxapp.officialaccount.utils.JacksonUtils;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@XmlRootElement(name = "xml")
public class NewsMessage extends Message {

    private int ArticleCount;


    private List<Article> Articles;

    public NewsMessage() {
        super();
        super.setMsgType(MessageEventTypeEnum.NEWS.getMsgType());
    }

    public NewsMessage(List<Article> articles) {
        super();
        super.setMsgType(MessageEventTypeEnum.NEWS.getMsgType());
        this.Articles = articles;
        this.ArticleCount = articles.size();
    }

    @XmlElement(name = "ArticleCount")
    public int getArticleCount() {
        return ArticleCount;
    }

    public void setArticleCount(int articleCount) {
        ArticleCount = articleCount;
    }

    @XmlElementWrapper(name = "Articles")
    @XmlElement(name = "item")
    public List<Article> getArticles() {
        return Articles;
    }

    public void setArticles(List<Article> articles) {
        Articles = articles;
    }

    @Override
    public String toCustomerMessage() {
        Map<String, Object> msg = new HashMap<>();
        msg.put("touser", getToUserName());
        msg.put("msgtype", MessageEventTypeEnum.NEWS.getMsgType());
        Map<String, Object> news = new HashMap<>();
        List<Map<String, Object>> articals = new ArrayList<>();
        for (int i = 0; i < getArticles().size(); i++) {
            // 最大允许8个图文
            if (i >= 8) {
                break;
            }
            Article article = getArticles().get(i);
            Map<String, Object> ar = new HashMap<>();
            ar.put("title", article.getTitle());
            ar.put("description", article.getDescription());
            ar.put("url", article.getUrl());
            ar.put("picurl", article.getPicUrl());
            articals.add(ar);
        }
        news.put("articles", articals);
        msg.put("news", news);
        return JacksonUtils.generate(msg);
    }
}
